package com.sxt.practiceapplication.activities;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.google.common.base.Strings;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.cache.CacheMode;
import com.lzy.okhttputils.callback.StringCallback;
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog;
import com.sxt.practiceapplication.R;
import com.sxt.practiceapplication.base.BaseActivity;
import com.sxt.practiceapplication.common.Constants;
import com.sxt.practiceapplication.common.ServerStatus;
import com.sxt.practiceapplication.common.Urls;
import com.sxt.practiceapplication.databinding.ActivityChangePasswordBinding;
import com.sxt.practiceapplication.entity.user.data.ChangePwdData;
import com.sxt.practiceapplication.utils.GsonBinder;
import com.sxt.practiceapplication.utils.LoginUser;
import com.sxt.practiceapplication.utils.Tools;

import java.util.Timer;
import java.util.TimerTask;

import okhttp3.Call;
import okhttp3.Response;

public class ChangePasswordActivity extends BaseActivity {

    private ActivityChangePasswordBinding changePasswordBinding;

    private boolean canSubmit;
    private boolean oldPwdEffective;
    private boolean newPwdEffective;
    private boolean newPwdAgainEffective;
    private EditText oldPassword;
    private EditText newPassword;
    private EditText newPasswordAgain;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        changePasswordBinding = ActivityChangePasswordBinding.inflate(getLayoutInflater());
        setContentView(changePasswordBinding.getRoot());

        initView();

        registerPwdChangeBroadcast();
    }

    private void initView() {

        oldPassword = changePasswordBinding.oldPassword;
        newPassword = changePasswordBinding.newPassword;
        newPasswordAgain = changePasswordBinding.newPasswordAgain;

        initEditTexts();

        initEnsureButton();
    }

    private void initEditTexts() {

        oldPassword.setOnKeyListener((v, keyCode, event) -> {
            if (event.getAction() == KeyEvent.ACTION_UP) {
                TextView oldPwdTip = changePasswordBinding.oldPwdTip;
                if (Strings.isNullOrEmpty(oldPassword.getText().toString())) {
                    oldPwdEffective = false;
                    oldPwdTip.setVisibility(View.VISIBLE);
                } else {
                    oldPwdEffective = true;
                    oldPwdTip.setVisibility(View.INVISIBLE);
                }
                checkCanSubmit();
            }
            return false;
        });

        newPassword.setOnKeyListener((v, keyCode, event) -> {
            if (event.getAction() == KeyEvent.ACTION_UP) {
                TextView newPwdTip = changePasswordBinding.newPwdTip;
                if (Strings.isNullOrEmpty(newPassword.getText().toString())) {
                    newPwdTip.setText("新密码不能为空");
                    newPwdEffective = false;
                    newPwdTip.setVisibility(View.VISIBLE);
                } else {
                    newPwdEffective = true;
                    newPwdTip.setVisibility(View.INVISIBLE);
                }
                checkCanSubmit();
            }
            return false;
        });

        newPasswordAgain.setOnKeyListener((v, keyCode, event) -> {
            if (event.getAction() == KeyEvent.ACTION_UP) {
                TextView newPwdAgainTip = changePasswordBinding.newPwdAgainTip;
                String newPasswordAgain = this.newPasswordAgain.getText().toString();
                String newPassword = this.newPassword.getText().toString();
                if (Strings.isNullOrEmpty(newPasswordAgain)) {
                    newPwdAgainTip.setText("请再次输入新密码");
                    newPwdAgainEffective = false;
                    newPwdAgainTip.setVisibility(View.VISIBLE);
                } else if (!newPassword.equals(newPasswordAgain)) {
                    newPwdAgainTip.setText("前后两次输入密码不一致");
                    newPwdAgainEffective = false;
                    newPwdAgainTip.setVisibility(View.VISIBLE);
                } else {
                    newPwdAgainEffective = true;
                    newPwdAgainTip.setVisibility(View.INVISIBLE);
                }
                checkCanSubmit();
            }
            return false;
        });
    }

    private void checkCanSubmit() {
        canSubmit = oldPwdEffective && newPwdEffective && newPwdAgainEffective;
        sendBroadcast(new Intent(Constants.PWD_EDIT_STATE_CHANGE));
    }

    private void initEnsureButton() {
        changePasswordBinding.ensureChangePwd.setOnClickListener(v ->
                changePassword(
                        oldPassword.getText().toString(),
                        newPassword.getText().toString()
                ));
        changePasswordBinding.ensureChangePwd.setClickable(false);
    }

    private void changePassword(String oldPassword, String newPassword) {
        OkHttpUtils.put(Urls.USER_CHANGE_PWD_URL)
                .tag(this)
                .cacheMode(CacheMode.NO_CACHE)
                .headers("Authorization", LoginUser.getCurrentUserData(ChangePasswordActivity.this).getToken())
                .params("oldPassword", oldPassword)
                .params("newPassword", newPassword)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String result, Call call, Response response) {
                        canSubmit = false;
                        sendBroadcast(new Intent(Constants.PWD_EDIT_STATE_CHANGE));
                        ChangePwdData rs = GsonBinder.toObj(result, ChangePwdData.class);
                        if (rs.getCode().equals(ServerStatus.SUCCESS.getCode())) {
                            QMUITipDialog tipDialog = showChangePwdResultDialog(rs.getMessage(), true);
                            new Timer().schedule(new TimerTask() {
                                @Override
                                public void run() {
                                    tipDialog.dismiss();
                                }
                            }, 1000);
                        } else {
                            QMUITipDialog tipDialog = showChangePwdResultDialog(rs.getMessage(), false);
                            new Timer().schedule(new TimerTask() {
                                @Override
                                public void run() {
                                    tipDialog.dismiss();
                                }
                            }, 1000);
                        }
                    }

                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        Tools.showErrorDialog(ChangePasswordActivity.this, "服务器错误");
                    }
                });
    }

    private QMUITipDialog showChangePwdResultDialog(String tip, boolean isSuccessful) {
        return Tools.showResultTipDialog(
                ChangePasswordActivity.this,
                tip
                , isSuccessful);
    }

    private void registerPwdChangeBroadcast() {
        registerReceiver(new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                TextView ensureChangePwd = changePasswordBinding.ensureChangePwd;
                if (canSubmit) {
                    ensureChangePwd.setClickable(true);
                    ensureChangePwd.setBackgroundResource(R.drawable.button_color_selector_enable);
                } else {
                    ensureChangePwd.setClickable(false);
                    ensureChangePwd.setBackgroundResource(R.drawable.button_color_selector_forbidden);
                }
            }
        }, new IntentFilter(Constants.PWD_EDIT_STATE_CHANGE));
    }

    @Override
    protected void exitActivity() {
        finish();
    }
}